package com.deng.eventflow.core.tmf;

import java.util.HashMap;
import java.util.Map;

public class CountDecimate extends Decimate {
    /**
     * The decimation interval
     */
    private final int m_interval;

    /**
     * Index of last event received
     */
    protected int m_current;

    /**
     * Creates a new count decimate processor with a decimation interval of 1
     */
    public CountDecimate()
    {
        this(1);
    }

    /**
     * Creates a new count decimate processor
     *
     * @param interval
     *          The decimation interval
     */
    public CountDecimate(int interval)
    {
        this(interval, false);
    }

    /**
     * Creates a new count decimate processor
     *
     * @param interval
     *          The decimation interval
     * @param should_process_last_inputs
     *          Default to false. Indicates if the processor should output the last
     *          input events of the trace even if it does not correspond to the
     *          decimation interval.
     */
    public CountDecimate(int interval, boolean should_process_last_inputs)
    {
        super(should_process_last_inputs);
        m_interval = interval;
        m_current = 0;
    }

    /**
     * Gets the decimation interval
     *
     * @return The interval
     */
    public int getInterval()
    {
        return m_interval;
    }

    @Override
    protected boolean shouldOutput()
    {
        return m_current == 0;
    }

    @Override
    protected void postCompute()
    {
        m_current = (m_current + 1) % m_interval;
    }

    @Override
    public void reset()
    {
        super.reset();
        m_current = 0;
    }

    @Override
    public CountDecimate duplicate(boolean with_state)
    {
        return new CountDecimate(m_interval, m_shouldProcessLastInputs);
    }

    /**
     * @since 0.10.2
     */
    @Override
    protected Object printState()
    {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("interval", m_interval);
        map.put("current", m_current);
        map.put("process-last", m_shouldProcessLastInputs);
        return map;
    }

    /**
     * @since 0.10.2
     */
    @SuppressWarnings("unchecked")
    @Override
    protected CountDecimate readState(Object o)
    {
        Map<String,Object> map = (Map<String,Object>) o;
        CountDecimate cd = new CountDecimate(((Number) map.get("interval")).intValue(),
                (Boolean) map.get("process-last"));
        cd.m_current = ((Number) map.get("current")).intValue();
        return cd;
    }
}
